package chapter1;

/**
 * @author ycj
 * @version 1.0
 * @description: TODO
 * @date 2022/5/16
 */
public class Source1_5 {
    public static void main(String[] args) {
        //获取处理器个数
        final int mount = Runtime.getRuntime().availableProcessors();

        Thread t;
        CountingTask countingTask = new CountingTask();


        for(int i=0;i<2*mount;i++){
            t=new CountingThread();
            t.start();
        }

        for(int i=0;i<2*mount;i++){
            t = new Thread(countingTask);
            t.start();
        }


    }
}


class Count{
    private int count;

    public void increment(){
        this.count++;
    }

    public int value(){
        return this.count;
    }
}


class CountingTask implements Runnable{
    private Count count=new Count();

    @Override
    public void run() {
        for(int i=0;i<=20;i++){
            Sleep();
            count.increment();
        }
        System.out.println("CountingTask:"+count.value());
    }

    private void Sleep(){
        try {
            Thread.sleep(80);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


class CountingThread extends Thread{
    private Count count=new Count();

    @Override
    public void run() {
        for(int i=0;i<=20;i++){
            Sleep();
            count.increment();
        }
        System.out.println("CountingThread:"+count.value());
    }


    private void Sleep(){
        try {
            Thread.sleep(80);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
